<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>MQTT-无塑地球</title>
</head>

<style>
</style>

<body>

<br>
<button type="button">点击出袋</button>
<br>

<script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>

<script>
    const clientId = 'mqttjs_' + Math.random().toString(16).substr(2, 8)
    const host = 'ws://106.55.164.145:8083/mqtt'
    const options = {
        username: 'scan_bag_iot_js_2022',
        password: 'd7ff96f54afc977ec3207c55a431e5fd1821edc822f939170c78663b93c81967',
        keepalive: 60,
        clientId: clientId,
        protocolId: 'MQTT',
        protocolVersion: 4,
        clean: true,
        reconnectPeriod: 1000,
        connectTimeout: 30 * 1000,
        will: {
            topic: 'WillMsg',
            payload: 'Connection Closed abnormally..!',
            qos: 0,
            retain: false
        },
    }

    console.log('Connecting mqtt client')
    const client = mqtt.connect(host, options)

    //连接错误
    client.on('error', (err) => {
        console.log('Connection error: ', err)
        client.end()
    })

    //订阅主题
    client.on('connect', () => {
        console.log('Client connected:' + clientId)
        client.subscribe('scan_bag_iot_js_macid_6610005', {qos: 0})
    })

    //接收消息Received
    client.on('message', (topic, message, packet) => {
        console.log(topic)
        console.log(message.toString())
    })

    //重连
    client.on('reconnect', () => {
        console.log('Reconnecting...')
    })

</script>

</body>
</html>
